﻿using System;
using System.IO;
using System.Linq;
using ICSharpCode.SharpZipLib.Zip;

namespace WindowsTest
{
    internal class UnZip
    {
        /// <summary>
        /// 解压缩方法
        /// </summary>
        /// <param name="path">压缩包存放路径</param>
        /// <param name="isToSameFolder">是否解压到同一目录</param>
        public static string Unzip(string path, bool isToSameFolder = true)
        {
            var parentFolderName = path.Substring(path.LastIndexOf('\\') + 1);
            var dir = new DirectoryInfo(path);
            FileInfo[] finfos = dir.GetFiles();
            if (finfos.Any())
            {
                foreach (var fileInfo in finfos)
                {
                    var zt = ZipType.Zip;
                    if (isZip(fileInfo.FullName, ref zt))
                    {
                        string folderName;
                        if (!isToSameFolder)
                        {
                            var subFolder = fileInfo.Name.Substring(0, fileInfo.Name.IndexOf('.'));
                            folderName = parentFolderName + "\\" + subFolder;
                        }
                        else
                        {
                            folderName = parentFolderName;
                        }

                        switch (zt)
                        {
                            case ZipType.Zip:
                                DecompressionZip(fileInfo, folderName);
                                break;
                            case ZipType.Rar:
                                DecompressionRar(fileInfo, folderName);
                                break;
                        }
                    }
                }
            }

            return parentFolderName;
        }

        /// <summary>
        /// 判断是否是压缩文件
        /// </summary>
        /// <param name="fullName">文件夹全称</param>
        /// <param name="zt">压缩文件类型</param>
        /// <returns>是否是压缩文件</returns>
        private static bool isZip(string fullName, ref ZipType zt)
        {
            var flag = false;
            var ex = fullName.Substring(fullName.LastIndexOf('.') + 1);
            if (ex.ToUpper() == "ZIP")
            {
                zt = ZipType.Zip;
                flag = true;
            }
            else if (ex.ToUpper() == "RAR")
            {
                zt = ZipType.Rar;
                flag = true;
            }
            return flag;
        }

        #region 打开解压缩文件

        /// <summary>
        /// 解压ZIP文件
        /// </summary>
        /// <param name="fileInfo"></param>
        /// <param name="batchID"></param>
        /// <returns></returns>
        public static FileInfo[] DecompressionZip(FileInfo fileInfo, String batchID)
        {
            var fi = new FileInfo[0];
            var zis = new ZipInputStream(File.OpenRead(fileInfo.FullName));
            try
            {
                ZipEntry zipEntry;
                while ((zipEntry = zis.GetNextEntry()) != null)
                {
                    if (zipEntry.Name != String.Empty)
                    {
                        if (zipEntry.IsDirectory)
                        {
                            Directory.CreateDirectory("temp\\" + batchID + "\\" + zipEntry.Name);
                        }
                        if (zipEntry.IsFile)
                        {
                            if (!Directory.Exists(@"temp\\" + batchID))
                                Directory.CreateDirectory(@"temp\\" + batchID);
                            FileStream streamWriter = File.Create("temp\\" + batchID + "\\" + zipEntry.Name);
                            var buf = new byte[2048];
                            while (true)
                            {
                                int size = zis.Read(buf, 0, buf.Length);
                                if (size > 0)
                                {
                                    streamWriter.Write(buf, 0, size);
                                }
                                else
                                {
                                    break;
                                }
                            }
                            streamWriter.Close();
                        }
                    }
                }

                var dir = new DirectoryInfo(@"temp\\" + batchID);
                if (dir.Exists)
                {
                    fi = dir.GetFiles();
                }
            }
            catch (Exception e)
            {
                LogService.Error(e);
                LogService.Info("解压文件" + fileInfo.Name + "失败");
            }
            finally
            {
                zis.Close();
            }
            return fi;
        }

        /// <summary>
        /// 解压RAR文件
        /// </summary>
        /// <param name="fileInfo"></param>
        /// <param name="batchID"></param>
        /// <returns></returns>
        public static FileInfo[] DecompressionRar(FileInfo fileInfo, String batchID)
        {
            var fi = new FileInfo[0];
            var un = new Unrar();
            try
            {
                if (!Directory.Exists(@"temp\\" + batchID))
                {
                    Directory.CreateDirectory(@"temp\\" + batchID);
                }
                un.Open(fileInfo.FullName, Unrar.OpenMode.Extract);
                while (un.ReadHeader())
                {
                    un.ExtractToDirectory(@"temp\\" + batchID);
                }

                var dir = new DirectoryInfo(@"temp\\" + batchID);
                if (dir.Exists)
                {
                    fi = dir.GetFiles();
                }
            }
            catch (Exception e)
            {
                LogService.Error(e);
                LogService.Info("解压文件" + fileInfo.Name + "失败");
            }
            finally
            {
                un.Close();
            }
            return fi;
        }

        #endregion
    }

    enum ZipType
    {
        Zip,
        Rar
    }
}